package com.oc.claimobs.bb.screens.camera.legacy;

import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import net.rim.blackberry.api.invoke.CameraArguments;
import net.rim.blackberry.api.invoke.Invoke;
import net.rim.device.api.applicationcontrol.ApplicationPermissions;
import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager;
import net.rim.device.api.io.file.FileSystemJournal;
import net.rim.device.api.io.file.FileSystemJournalEntry;
import net.rim.device.api.io.file.FileSystemJournalListener;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.EventInjector;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

import com.oc.claimobs.bb.ScreenFlow;
import com.oc.utils.Style;

public class PreviewPictureLegacyScreen extends MainScreen implements FieldChangeListener,
		FileSystemJournalListener {

	public PreviewPictureLegacyScreen() {
		super(MainScreen.NO_VERTICAL_SCROLLBAR
				| MainScreen.NO_HORIZONTAL_SCROLL
				| MainScreen.NO_HORIZONTAL_SCROLLBAR);
		init();
	}

	private static final int IMAGE_SCALING = 5;
	private Bitmap backgroundBitmap;
	private VerticalFieldManager vfm = null;

	private byte[] picture = null;

	private boolean nopicture = true;

	private void init() {

		// The background image.
		backgroundBitmap = Bitmap.getBitmapResource("img/title_back.png");
		
		vfm = new VerticalFieldManager(
				VerticalFieldManager.NO_VERTICAL_SCROLL
						| VerticalFieldManager.NO_VERTICAL_SCROLLBAR
						| VerticalFieldManager.USE_ALL_WIDTH
						| VerticalFieldManager.NON_FOCUSABLE
						| VerticalFieldManager.USE_ALL_HEIGHT) {

			// Override the paint method to draw the background image.
			public void paint(Graphics graphics) {
				// Draw the background image and then call paint.
				graphics.drawBitmap(0, 0, Style.getScreenWidht(), 40, backgroundBitmap, 0, 0);
				super.paint(graphics);
			}
		};

		initPreview();
		
		log = new LabelField(" " , Field.FIELD_LEFT | Field.NON_FOCUSABLE);
		vfm.add(log);
		
		add(vfm);
	}

	private void previewPicture(byte[] raw) {
		this.nopicture = false;

		this.picture = raw;

		vfm.delete(hfm1);
		vfm.delete(hfm2);

		initPreview();
	}
	LabelField log;
	private HorizontalFieldManager hfm1 = null;
	private HorizontalFieldManager hfm2 = null;

	String llog; 
	public void log(String text){

		if(!true){
			llog = text + "\n" + llog;
			UiApplication.getUiApplication().invokeLater(new Runnable() {
				public void run() {
					log.setText(llog);
				}
			});
		}

	}
	
	ButtonField cancelButton = null;
	
	private void initPreview() {

		hfm1 = new HorizontalFieldManager(Field.FIELD_HCENTER);
		hfm2 = new HorizontalFieldManager(Field.FIELD_HCENTER);

		Bitmap image;
		if (nopicture == true) {
			image = Bitmap.getBitmapResource("img/nopic.png");
		} else {
			image = Bitmap.createBitmapFromBytes(picture, 0, -1, IMAGE_SCALING);
		}

		BitmapField imageField = new BitmapField(image);
		imageField.setMargin(60, 0, 0, 0);
		hfm1.add(imageField);

		cancelButton = new ButtonField("Capturar");
		cancelButton.setChangeListener(this);
		
		if (nopicture == false) {
			ButtonField photoButton = new ButtonField("Siguiente");
			photoButton.setChangeListener(new FieldChangeListener() {

				public void fieldChanged(Field field, int context) {

					if (!savePicture(picture)) {
						return;
					}

					try {
						Screen screen = ScreenFlow.getInstance().getNext("");
						UiApplication.getUiApplication().pushScreen(screen);
						UiApplication.getUiApplication().popScreen(
								ScreenFlow.getInstance().getFOTO_PAGE());
					} catch (IllegalArgumentException e) {
					}
				}
			});

			hfm2.add(photoButton);
		} else {
			hfm2.add(cancelButton);
		}

		//
		vfm.add(hfm1);
		vfm.add(hfm2);
		
		
		requestPermissions();
	}
	
	ApplicationPermissions newPermissions;
	private void requestPermissions(){
		ApplicationPermissions permissions = ApplicationPermissionsManager.getInstance().getApplicationPermissions();

		int[] xp = new int[]{ApplicationPermissions.PERMISSION_PHONE,
				ApplicationPermissions.PERMISSION_WIFI,
				ApplicationPermissions.PERMISSION_RECORDING,
				ApplicationPermissions.PERMISSION_SECURITY_DATA,
				ApplicationPermissions.PERMISSION_INPUT_SIMULATION,
				ApplicationPermissions.PERMISSION_INTERNET,
				ApplicationPermissions.PERMISSION_LOCATION_DATA,
				ApplicationPermissions.PERMISSION_MEDIA};
		
		for( int p = 0 ; p < xp.length ; p++){
			if(!permissions.containsPermissionKey(p))
			{
				newPermissions = new ApplicationPermissions();
				newPermissions.addPermission(xp[p]);
				
				log("request permissions later ");
				UiApplication.getUiApplication().invokeLater(new Runnable() {
					
					public void run() {

						log("request permissions" + newPermissions.getPermissionKeys());
						
						if(newPermissions != null){
						
						ApplicationPermissionsManager.getInstance().invokePermissionsRequest(newPermissions);
						
						}
						
					}
				});
			}
		}
	}
	
	

	public void fieldChanged(Field field, int context) {

		UiApplication.getUiApplication().addFileSystemJournalListener(this);
		
		Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA, new CameraArguments());
	}
	
	public boolean savePicture(byte[] raw) {
		try {
			ScreenFlow.getInstance().setLastPicture(raw);
			return true;
		} catch (Exception e) {
			System.out
					.println("ERROR " + e.getClass() + ":  " + e.getMessage());
		}
		return false;
	}

	protected boolean invokeAction(int action) {
		boolean handled = super.invokeAction(action);

		if (!handled) {
			switch (action) {
			case ACTION_INVOKE: // Trackball click.
			{
				log("click");
				return true;
			}
			}
		}
		return handled;
	}


	public void close() {
		this.setDirty(false);
		super.close();
	}

	String imgpath;

	public void fileJournalChanged() 
	{
		FileSystemJournalEntry entry = null;
	
		try{
				long lastUSN = 0;
		
				long USN = FileSystemJournal.getNextUSN();
				for (long i = USN - 1; i >= lastUSN; --i) {
					entry = FileSystemJournal.getEntry(i);
					if (entry != null) {
						if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED) {
							if (entry.getPath().indexOf(".jpg") != -1) {
								//
								try {
									UiApplication.getUiApplication().removeFileSystemJournalListener(this);
								} catch(Exception ex){
									
								}
								
								log("found :" + entry.getPath());
								
								lastUSN = USN;
								imgpath = entry.getPath();

								Thread.currentThread().sleep(2000);
								
								UiApplication.getUiApplication().invokeAndWait( new Runnable() { 
									 public void run() { 
										 byte[] raw = getImage(imgpath);
										 log("picture == null :" +(picture == null));
										 previewPicture(raw);
									 } 
								 });
								
								break;
							}
						}
					}
				}

		} catch(Exception ex){
			log("Error@fileJournalChanged :" + ex.getClass() + " " + ex.getMessage());
		}

	}

	private byte[] getImage(String url) {
		byte[] data = null;
		FileConnection fconn = null;
		try {
			fconn = (FileConnection) Connector.open("file://" + url);
			if (fconn.exists()) {
				InputStream input = fconn.openInputStream();
				data = new byte[(int) fconn.fileSize()];
				input.read(data, 0, data.length);
			}
		} catch (Exception e) {
			Dialog.alert("No se encontro el archivo");
		} finally {
			try {
				fconn.close();
			} catch (Exception e) {}
		}
		return data;
	}

}
